package com.example.edu.Filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalTime;

@WebFilter(urlPatterns = "/api/*", asyncSupported = true)// 这里指定过滤器作用的 URL
public class TimeFilter implements Filter {

    private static final LocalTime MAINTENANCE_START = LocalTime.of(4, 25);
    private static final LocalTime MAINTENANCE_END = LocalTime.of(4, 40);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作，可以不需要实现
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        LocalTime currentTime = LocalTime.now();

        // 检查当前时间是否在维护时间段内
        if (!currentTime.isBefore(MAINTENANCE_START) && !currentTime.isAfter(MAINTENANCE_END)) {
            // 如果是，返回一个自定义错误码和消息
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // 503 Service Unavailable
            httpResponse.setContentType("application/json");
            String jsonResponse = "{\"error_code\": 1001, \"message\": \"系统维护中，请稍后再试\"}";
            response.getWriter().write(jsonResponse);
            return;
        }

        // 如果不是维护时间段，则继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁时的清理操作，可以不需要实现
    }
}

